<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Template extends Base
{
    protected $table = 'template_view';
    protected $templateLayoutTable = 'template_layout';
    protected $templateBlockTable = 'template_block';
    protected $templateBlockTypeTable = 'template_block_type';
    protected $templateBlockStyleTable = 'template_block_style';
    protected $templateBlockSourceTable = 'template_block_source';

    protected $redisKeyTemplateView = 'TEMPLATE:VIEW';// 页面模板缓存Key
    protected $redisKeyTemplateViewPreviewUser = 'TEMPLATE:VIEW_PREVIEW_USER';// 页面模板预览缓存Key

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 页面缓存-设置预览-缓存（每次都重新数据拉取覆盖cache）
     *
     * @param int $type 类型 默认 0=读取，1=写入
     * @param string $userIds 用户ID组，逗号分隔
     * @return string
     * */
    public function setTemplateViewPreviewUserCache($type = 0, $userIds = '')
    {
        $result = '';
        switch ($type) {
            case 0:
                if (Redis::exists($this->redisKeyTemplateViewPreviewUser)) {
                    $result = Redis::get($this->redisKeyTemplateViewPreviewUser);
                }
                break;
            case 1:
                $ret = Redis::set($this->redisKeyTemplateViewPreviewUser, $userIds);
                if ($ret) {
                    $result = $userIds;
                }
                break;
            default:
                break;
        }
        return $result;
    }

    /**
     * 页面缓存-发布
     *
     * @param string $viewAliasName 页面别名
     * @return bool
     * */
    public function setTemplateViewReleaseCache($viewAliasName)
    {
        $template = $this->getTemplateView($viewAliasName);
        return Redis::hmset($this->redisKeyTemplateView, $viewAliasName, json_encode($template, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 页面缓存-读取
     *
     * @param string $viewAliasName 页面别名
     * @param int $userId 用户ID
     * @param int $blockId 块级ID
     * @return array
     * */
    public function getTemplateViewCache($viewAliasName, $userId = 0, $blockId = 0)
    {
        $data = [];

        do {
            // 判断是否可以 执行DB 预览新数据
            if (Redis::exists($this->redisKeyTemplateViewPreviewUser)) {
                $getPreviewUser = Redis::get($this->redisKeyTemplateViewPreviewUser);
                $getPreviewUser = explode(',', $getPreviewUser);
                if (!empty($getPreviewUser) and $userId > 0 and in_array($userId, $getPreviewUser)) {
                    $data = $this->getTemplateView($viewAliasName);
                    break;
                }
            }

            // 取出缓存模板数据
            if (Redis::hexists($this->redisKeyTemplateView, $viewAliasName)) {
                $template = Redis::hget($this->redisKeyTemplateView, $viewAliasName);
                $template = json_decode($template, true);
                if (!empty($template) and !empty($template)) {
                    $data = $template;
                    break;
                }
            }
        } while (false);

        // 取出单条模块数据
        if (!empty($data) and $blockId > 0) {
            $templateBlockKeyIdArray = array_column($data['template_block'], 'block_id', 'block_id');
            if (array_key_exists($blockId, $templateBlockKeyIdArray)) {
                $templateBlockIdArray = array_column($data['template_block'], 'block_id');
                $templateBlockIdIndex = array_search($blockId, $templateBlockIdArray);
                $data = $data['template_block'][$templateBlockIdIndex];
            } else {
                $data = [];
            }
        }

        return $data;
    }

    /**
     * 获取页面
     *
     * @param string $viewAliasName 页面别名
     *
     * @return array
     * */
    public function getTemplateView($viewAliasName)
    {
        $template = $this->getTemplateViewLeftJoinLayoutSingle($viewAliasName);
        if (!empty($template)) {
            $template['template_block'] = $this->getTemplateBlockList(['layout_id' => $template['layout_id']]);
        }
        return $template;
    }

    /**
     * 视图左连表布局-查询单条
     * @param string $viewAliasName 页面别名
     * @return array
     * */
    public function getTemplateViewLeftJoinLayoutSingle($viewAliasName)
    {
        $template = DB::table($this->table)
            ->leftJoin($this->templateLayoutTable, $this->table . '.layout_id', '=', $this->templateLayoutTable . '.layout_id')
            ->where('view_alias_name', '=', $viewAliasName)
            ->first([
                // $this->table . '.view_id',
                $this->table . '.view_name',
                // $this->table . '.view_alias_name',
                $this->table . '.type as view_type',
                $this->table . '.action as view_action',
                DB::raw("coalesce(zb_{$this->templateLayoutTable}.`layout_id`,0) as layout_id"),
                DB::raw("coalesce(zb_{$this->templateLayoutTable}.`layout_name`,'') as layout_name"),
            ]);
        return self::objToArray($template);
    }

    ################# 视图 ####################################################################################

    /**
     * 视图-查询多条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateViewList($condition = [])
    {
        $template = DB::table($this->table)
            ->where($condition)
            ->get()
            ->toArray();
        return self::objToArray($template);
    }

    /**
     * 视图-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateViewSingle($condition)
    {
        $template = DB::table($this->table)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建视图
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateView($data)
    {
        return DB::table($this->table)->insertGetId($data);
    }

    /**
     * 更新视图
     *
     * @param array $condition 条件
     * @param array $data 数据
     * @return bool
     * */
    public function updateTemplateView($condition, $data)
    {
        return DB::table($this->table)->where($condition)->update($data);
    }

    /**
     * 删除视图
     *
     * @param int $viewId 视图ID
     * @return bool
     * */
    public function removeTemplateView($viewId)
    {
        return DB::table($this->table)->where(['view_id' => $viewId])->delete();
    }

    ################# 布局 ####################################################################################

    /**
     * 布局-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateLayoutSingle($condition)
    {
        $template = DB::table($this->templateLayoutTable)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建布局
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateLayout($data)
    {
        return DB::table($this->templateLayoutTable)->insertGetId($data);
    }

    /**
     * 删除布局
     *
     * @param array $condition 条件
     * @return bool
     * */
    public function removeTemplateLayout($condition)
    {
        return DB::table($this->templateLayoutTable)->where($condition)->delete();
    }

    ################# 块级 ####################################################################################

    /**
     * 块级-查询多条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateBlockList($condition)
    {
        $condition['is_show_block'] = 1;

        $template = DB::table($this->templateBlockTable)
            ->where($condition)
            ->orderBy('sort_number', 'asc')
            ->get()
            ->toArray();
        return self::objToArray($template);
    }

    /**
     * 块级-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateBlockSingle($condition)
    {
        $template = DB::table($this->templateBlockTable)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建块级
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateBlock($data)
    {
        return DB::table($this->templateBlockTable)->insertGetId($data);
    }

    /**
     * 更新块级
     *
     * @param array $condition 条件
     * @param array $data 数据
     * @return bool
     * */
    public function updateTemplateBlock($condition, $data)
    {
        return DB::table($this->templateBlockTable)->where($condition)->update($data);
    }

    /**
     * 删除块级
     *
     * @param array $condition 条件
     * @return bool
     * */
    public function removeTemplateBlock($condition)
    {
        return DB::table($this->templateBlockTable)->where($condition)->delete();
    }

    ################# 以下逻辑暂时忽略 不对外开放 ####################################################################################

    ################# 块级 类型 ####################################################################################

    /**
     * 块级类型-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateBlockTypeSingle($condition)
    {
        $template = DB::table($this->templateBlockTypeTable)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建块级类型
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateBlockType($data)
    {
        return DB::table($this->templateBlockTypeTable)->insertGetId($data);
    }

    /**
     * 删除块级类型
     *
     * @param array $condition 条件
     * @return bool
     * */
    public function removeTemplateBlockType($condition)
    {
        return DB::table($this->templateBlockTypeTable)->where($condition)->delete();
    }

    ################# 块级 样式 ####################################################################################

    /**
     * 块级样式-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateBlockStyleSingle($condition)
    {
        $template = DB::table($this->templateBlockStyleTable)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建块级样式
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateBlockStyle($data)
    {
        return DB::table($this->templateBlockStyleTable)->insertGetId($data);
    }

    /**
     * 删除块级样式
     *
     * @param array $condition 条件
     * @return bool
     * */
    public function removeTemplateBlockStyle($condition)
    {
        return DB::table($this->templateBlockStyleTable)->where($condition)->delete();
    }

    ################# 块级 数据来源 ####################################################################################

    /**
     * 块级数据来源-查询单条
     *
     * @param array $condition 条件
     * @return array
     * */
    public function getTemplateBlockSourceSingle($condition)
    {
        $template = DB::table($this->templateBlockSourceTable)
            ->where($condition)
            ->first();
        return self::objToArray($template);
    }

    /**
     * 创建块级数据来源
     *
     * @param array $data 数据
     * @return bool
     * */
    public function createTemplateBlockSource($data)
    {
        return DB::table($this->templateBlockSourceTable)->insertGetId($data);
    }

    /**
     * 删除块级数据来源
     *
     * @param array $condition 条件
     * @return bool
     * */
    public function removeTemplateBlockSource($condition)
    {
        return DB::table($this->templateBlockSourceTable)->where($condition)->delete();
    }
}